$(function () {

    window.close_chat = function () {

        chat_data.selToID = null;
        chat_data.selType = null;
        chat_data.selKey = null;
        chat_data.goodsstore_id = 0;
        chat_data.selToRealname = null;
        chat_data.msglist = [];
        chat_data.show_img_talk = false;
        chat_data.show_img_talk_more = false;
        chat_data.show_contact = true;
        chat_data.show_talk = false;

        chat_data.program_id = null;
        chat_data.live_status = false;
        chat_data.live_config = {};

        webim.setAutoRead(chat_data.selSess, false, true);
        chat_data.selSess = null;
        document.setTitle("华迅直购");
    };

    var me_data = {
        baseConfig: baseConfig,
        user: {}
    };
    var tab_me = Vue.extend({
        template: "#tab_me",
        data: function () {
            return me_data
        },
        methods: {
            show_head_img: window.show_head_img,
            go_address: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './user_address.html'
                });

            },
            go_about_me: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './about_me.html'
                });

            },

            go_pro_orders: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './pro_orders.html'
                });

            },
            go_share_me: function () {
                api.sys.get_sys_data({flag: "tui_yi_tui"}).then(function (value) {
                    location.href = value.result.data;
                    // Magiclamp.mcConfirm3("提示", "点击首页右上角分享给朋友购买", value.result.data, function () {
                    // }, function () {
                    //     var get_news_id = function(url){
                    //         var str = url;
                    //         var end_index = str.indexOf(".html");
                    //         var new_str = str.substring(0, end_index);
                    //         var s = new_str.split("/");
                    //         if(s.length>0){
                    //             return parseInt(s[s.length-1])
                    //         }else{
                    //             return 0;
                    //         }
                    //
                    //     };
                    //     api.an.save_pay_shared({news_id:get_news_id(value.result.data)}).then(function () {
                    //         console.log("付款后点击软文的记录")
                    //     })
                    // })
                });
                // api.sys.get_userinfo().then(function (data) {
                //     location.href = './tuishou_goods.html'
                // });

            },
            go_to_userinfo: function () {
                location.href = './user_info.html'

            },
            go_shared_order: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './shared_orders.html'
                });

            },
            go_guanzhu_me: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './guan_zhu.html'
                });

            },
            logout: function () {
                api.sys.logout().then(function (value) {
                    location.href = './home.html'
                })
            },
            go_change_password: function () {
                api.sys.get_userinfo().then(function (data) {
                    location.href = './change_password.html'
                });

            },
            go_my_orders: function () {
                location.href = './orders.html'
            },
            unbind_logout: function () {
                location.href = "/sys/wx_unbind_logout";
            },
            login_wx: function () {
                login_mogu(function () {

                }, "home", null, true);
            }
        }
    });

    var cart_data = {
        baseConfig: baseConfig,
        is_all: false,
        is_all_checked: 1,
        cart_list: [],
        goods_list: [],
        goods_ids: [],
        goods_num: 0
    };

    function checkAll() {
        cart_data.goods_ids.splice(0, cart_data.goods_ids.length);
        cart_data.is_all_checked = 0;
        if (!cart_data.is_all) {
            cart_data.cart_list.forEach(function (item) {
                if (item.is_active) {
                    cart_data.goods_ids.push(item.goods_id);
                }

            });
            cart_data.is_all_checked = 1;
        }
        cart_data.is_all = !cart_data.is_all;

    }

    var tab_cart = Vue.extend({
        template: "#tab_cart",
        data: function () {
            return cart_data
        },
        methods: {
            price_filter: price_filter,
            cart_pay: function (goods_ids) {
                var cart_list_ids = [];
                $.each(goods_ids, function (index, goods_id) {
                    $.each(cart_data.cart_list, function (index, c_goods) {
                        if (c_goods.goods_id == goods_id) {
                            cart_list_ids.push(c_goods.id)
                        }
                    })
                })
                api.lorder.create_order({cart_list: cart_list_ids.join(',')}).then(function (data) {
                    if (data.result.is_need_pay_order) {
                        Magiclamp.mcConfirm("提示", data.message, null, function () {
                            home.toggleTabs("tab_order");
                        });
                    } else if (data.result.is_need_pay_order == false && data.result.is_new_goods) {
                        api.sys.get_sys_data({flag: "buy_repeat_new_goods_url"}).then(function (value) {
                            Magiclamp.mcConfirm4("提示", "您已经购买过【新用户商品】，欢迎前往购买其他商品。", value.result.data, function () {
                            }, function () {

                            })
                        });
                    } else {
                        var payorder_id = data.result.id;
                        location.href = './pay.html?payorder_id=' + payorder_id
                    }

                })
            },
            delete_cart: function (c_goods) {
                Magiclamp.mcConfirm("提示", "从购物删除商品？", null, function () {
                    api.lgoods.delete_carts({cart_id_list: c_goods.id}).then(function (data) {
                        Magiclamp.mcAlert("提示", data.message, null, function () {
                            c_goods.is_active = false;
                            cart_data.is_all = false;
                            checkAll();
                        });
                        home.refresh_cart();
                    });
                });
            },
            go_goods_detail: function (goods_id) {
                location.href = 'goods.html?goods_id=' + goods_id
            },
            pop_num: function (c_goods) {
                if (c_goods.num == 1) {
                    Magiclamp.mcAlert("提示", "购买数量不能为0", null, function () {
                    });
                    return;
                }

                var goods_id = c_goods.goods_id;
                api.lgoods.update_cart({goods_id: goods_id, num: c_goods.num - 1}).then(function (data) {
                    c_goods.num -= 1;
                    if (c_goods.num <= 0) {
                        c_goods.is_active = false;
                        cart_data.is_all = false;
                        checkAll();
                    }
                });
                return false;
            },
            add_num: function (c_goods) {

                var goods_id = c_goods.goods_id;
                api.lgoods.update_cart({goods_id: goods_id, num: c_goods.num + 1}).then(function (data) {
                    c_goods.num += 1;
                });
                return false;
            },
            checkAll: function () {
                checkAll();
            },
            refresh_checkAll: function () {
                setTimeout(function () {
                    var is_all = true;
                    cart_data.cart_list.forEach(function (item) {
                        if (item.is_active) {
                            var checked = false;
                            cart_data.goods_ids.forEach(function (obj) {
                                if (obj == item.goods_id) {
                                    checked = true;
                                }
                            });
                            if (!checked) {
                                is_all = false;
                            }
                        }

                    });
                    if (is_all) {

                        cart_data.is_all_checked = 1;
                        cart_data.is_all = true;
                    } else {

                        cart_data.is_all_checked = 0;
                        cart_data.is_all = false;
                    }
                }, 200);

            },
            price_all: function (goods_ids) {
                var prices = 0;
                $.each(goods_ids, function (index, goods_id) {
                    $.each(cart_data.cart_list, function (index, c_goods) {
                        if (c_goods.goods_id == goods_id) {
                            prices += (c_goods.goods__price - c_goods.goods__bu_tie_price) * c_goods.num
                        }
                    });
                });
                return cart_data.cart_list.prices = prices
            }
        }
    });


    function query_un_pay_order_info_list() {
        api.lorder.query_pay_order_info_list({
            charge_status: '0,1,3',
            page_index: order_data.no_page_index + 1
        }).then(function (data) {
            // order_data.un_pay_order_list = data.result.list;
            order_data.no_page_index = data.result.page_index;
            order_data.no_page_count = data.result.page_count;
            _(data.result.list).each(function (item) {
                order_data.un_pay_order_list.push(item);
                item['goods_num'] = 0;
                _(item.goods_order_list).each(function (order) {
                    _(order.goods_order_item_list).each(function (goods) {
                        item['goods_num'] += goods.num;

                    });
                });

            });
        });
    }

    function query_pay_order_info_list() {
        api.lorder.query_goods_order_list({
            status: '1',
            goods_status: '0,1,2,3',
            page_index: order_data.pay_page_index + 1
        }).then(function (data) {
            // order_data.goods_order_list = data.result.list;
            order_data.pay_page_index = data.result.page_index;
            order_data.pay_page_count = data.result.page_count;
            _(data.result.list).each(function (item) {
                // if(order_data.goods_order_list.length>2){
                //     return
                // }
                order_data.goods_order_list.push(item);
                item['goods_num'] = 0;
                _(item.goods_order_item_list).each(function (goods) {
                    item['goods_num'] += goods.num;
                });
                if (item.buy_files_json) {
                    item['buy_files_json_obj'] = JSON.parse(item.buy_files_json);
                } else {
                    item['buy_files_json_obj'] = [];
                }
            });
        });
    }

    function query_goods_order_list() {
        api.lorder.query_finish_goods_order_list({page_index: order_data.over_page_index + 1}).then(function (data) {
            // order_data.pay_order_list = data.result.list;
            order_data.over_page_index = data.result.page_index;
            order_data.over_page_count = data.result.page_count;
            _(data.result.list).each(function (item) {
                order_data.pay_order_list.push(item);
                item['goods_num'] = 0;
                _(item.goods_order_item_list).each(function (goods) {
                    item['goods_num'] += goods.num;
                });
                if (item.buy_files_json) {
                    item['buy_files_json_obj'] = JSON.parse(item.buy_files_json);
                } else {
                    item['buy_files_json_obj'] = [];
                }

            });
        });
    }


    var default_data = {
        baseConfig: baseConfig,
        user_id: 0,
        show_default_bar: false,
        show_default_bar_list: false,
        show_share_bar: false,
        show_pengyou_dongtai_images: false,
        comment_line_list:[],
        imagewheelA: [],
        imagewheelB: [],
        imagewheelC: [],
        imagewheelG: [],
        imagewheelAA: [],
        imagewheelAB: [],
        imagewheelAC: [],
        imagewheelAD: [],
        imagewheelAE: [],
        imagewheelAF: [],
        imagewheelAG: [],
        imagewheelAH: [],
        flag_group_list: [],
        friend_goods_list: [],
        home_pro_list: [],
        start_list:[{type:1, index:0},{type:1, index:1},{type:1, index:2},{type:1, index:3},{type:1, index:4}],

    };

    function query_default_page_image_wheel_list() {
        api.sys.get_image_wheel_info().then(function (data) {
            if(data.result.A!=undefined){
                default_data.imagewheelA = data.result.A;
            }

            if(data.result.B!=undefined){
                default_data.imagewheelB = data.result.B;
            }
            if(data.result.C!=undefined){
                default_data.imagewheelC = data.result.C;
            }
            if(data.result.G!=undefined){
                default_data.imagewheelG = data.result.G;
            }
            if(data.result.flag_group_list!=undefined){
                default_data.flag_group_list = data.result.flag_group_list;
            }


        });
    }
    function query_goods_by_hao_ping_pro_home_list() {
        api.lgoods.query_goods_by_hao_ping_pro_home_list().then(function (data) {
            _(data.result.list).each(function (item) {
                default_data.home_pro_list .push(item);
                if(item.file_type==0){

                }else if(item.file_type==1){
                    item.files_json = JSON.parse(item.files_json);
                }else if(item.file_type==2){
                    item.video_obj = JSON.parse(item.videos_json);

                }

            });
        });
    }
    function query_friend_goods_list(cb) {
        api.an.query_firend_buy_goods_list().then(function (data) {
            default_data.friend_goods_list = [];
            default_data.user_id = parseInt(client_storage("user_id"));
            _(data.result.list).each(function (item) {
                try{
                    item.files_list = JSON.parse(item.files_json);
                    if(item.files_list.length>4){
                        item.files_list.length = 4;
                    }
                    default_data.friend_goods_list.push(item);
                }catch (e) {

                }

            });
            api.an.query_firend_buy_goods_list({page_index:2}).then(function (data) {
                _(data.result.list).each(function (item) {
                    try{
                        item.files_list = JSON.parse(item.files_json);
                        if(item.files_list.length>4){
                            item.files_list.length = 4;
                        }
                        default_data.friend_goods_list.push(item);
                    }catch (e) {

                    }

                })

                if(cb){
                    cb();
                }

            });

            query_goods_by_comment_line_list();

        });
    }

    function query_goods_by_comment_line_list() {
        api.lgc.query_goods_by_comment_line_list({}).then(function (value) {
            default_data.comment_line_list = value.result.list;

            _(default_data.comment_line_list).each(function (item) {
                var start_time = moment(item.last_time);
                var now = moment();
                var minutes = now.diff(start_time, 'minutes');
                if(minutes<60){
                    item.last_time_str = minutes + "分钟";
                }else{
                    item.last_time_str = now.diff(start_time, 'hours') + "小时";
                }
                item.is_active = true;
            });
            if(default_data.comment_line_list.length>0){
                default_data.show_default_bar = true;
            }else{
                default_data.show_default_bar = false;
            }
        })
    }
    var tab_default = Vue.extend({
        template: "#tab_default",
        data: function () {
            return default_data
        },
        methods: {
            price_filter: price_filter,
            get_fengmian:function(img_url1, img_url2){
                if(img_url1){
                    return baseConfig.qn_host + img_url1+'?imageView2/1/w/270/h/270';
                }else if(img_url2){
                    return baseConfig.qn_host + img_url2+'?imageView2/1/w/270/h/270';
                }
            },
            show_big_pengyou_img: function (item, fileurl) {
                // program_data.show_pengyou_dongtai = false;
                default_data.show_pengyou_dongtai_images = true;
                var width = window.innerWidth
                    || document.documentElement.clientWidth
                    || document.body.clientWidth;
                var height = window.innerHeight
                    || document.documentElement.clientHeight
                    || document.body.clientHeight;
                setTimeout(function () {
                    var pswpElement = document.getElementById("all_pengyou_pswp");

                    var items = [];
                    var index = 0;

                    _(item.files_json).each(function (sub, i) {
                        items.push({src: baseConfig.qn_host + sub.fileurl +'?imageView2/0/w/'+width+'/h/'+(width*4/3), w: width, h: (width*4/3)})
                        if (sub.fileurl == fileurl) {
                            index = i;
                        }
                    })

                    var options = {
                        // optionName: 'option value'
                        // for example:
                        mainClass: 'pswp--minimal--dark',
                        index: index, // start at first slide

                    };

                    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                    gallery.listen('close', function () {
                        // program_data.show_pengyou_dongtai = true;
                        default_data.show_pengyou_dongtai_images = false;
                    });
                    gallery.init();
                }, 200);

            },

            open_pro_user:function(uid){
                location.href = 'pro_user_goods.html?user_id='+uid;
            },
            open_pro_user_goods:function(gid, uid){
                location.href = 'goods.html?goods_id='+gid+'&pro_user_id='+uid;
            },


            open_newuser_goods: function () {
                client_storage("is_new_user", "true");
                location.href = 'home_fenlei.html';
            },

            open_pro_goods: function () {
                location.href = 'home_pro_goods.html';
            },
            open_home_fenlei_goods: function (gid) {
                location.href = 'home_fenlei_share.html?fenlei_id='+gid;
            },
            alert_limit_pro: function () {
                api.sys.get_sys_data({flag: "pro_goods_msg"}).then(function (value) {
                    Magiclamp.mcAlert("提示", value.result.data);
                });

            },
            open_newshuiguo_goods: function () {
                client_storage("home_fenlei_live_type_id", "111");
                location.href = 'home_fenlei.html';
            },
            open_difangtechan_goods: function () {
                client_storage("home_fenlei_live_type_id", "107");
                location.href = 'home_fenlei.html';
            },
            open_payorder: function (payorder_id) {
                location.href = 'pay.html?payorder_id=' + payorder_id;
            },
            go_to_friend_set: function () {
                location.href = 'set_friends_step.html';
            },
            open_order_info: function (order_id) {
                location.href = 'user_goods_orders.html?goods_order_id=' + order_id;
            },
            show_goods_order_map: function (order) {
                location.href = 'goods_buyer_map.html?goodsstore_id=' + order.goodsstore_id + "&uid=" + order.buyer_id;
            },
            open_dispute_order_info: function (order_id) {
                location.href = 'user_dispute_goods_orders.html?dispute_id=' + order_id;
            },
            delete_payorder: function (payorder) {
                Magiclamp.mcConfirm("提示", "确认删除订单么？", null, function () {
                    api.lorder.delete_order({pay_order_id: payorder.id}).then(function (data) {
                        Magiclamp.mcAlert("提示", data.message);
                        payorder.is_active = false;

                        html_data.un_pay_order_list = _(html_data.un_pay_order_list).filter(function (item) {
                            return item.is_active;
                        });
                    });
                });

            },
            dispute_goods_order: function (goods_order) {
                Magiclamp.mcConfirm("提示", "确认投诉订单么？", null, function () {
                    api.lorder.dispute_goods_order({order_id: goods_order.id}).then(function (data) {
                        Magiclamp.mcAlert("提示", data.message);
                        goods_order.dispute_step = 1
                    })
                });
            },
            ping_lun: function (goods, comment) {
                var title = "评论";
                var to_user_id = "";
                if(comment){
                    title = "对 "+comment.user__realname+" 说:"
                    to_user_id = comment.user_id;
                }
                Magiclamp.mcPromptPingLun(title, "", function (content) {
                    api.lgc.create_goods_comment({goods_id: goods.id,content:content, to_user_id:to_user_id}).then(function (data) {
                        Magiclamp.mcAlert("提示", "评论成功");
                        query_friend_goods_list(function () {
                            setTimeout(function () {
                                location.href = '#goods_id' + goods.id;
                            }, 200);

                        });
                    })
                });
            },
            buy_date_ts: function (info) {
                var realname = info.user__realname;
                if (realname == undefined) {
                    realname = info.goods_order__user__realname;
                }
                var title = realname.substring(0, 1);
                for (var i = 0; i < realname.length; i++) {
                    title += "*"
                }

                Magiclamp.mcAlert("提示", title + "于" + info.create_time.substring(0, 10)+"购买。");
            },
            first_name:function(realname){
                var title = realname.substring(0, 1);
                for (var i = 0; i < realname.length; i++) {
                    title += "*"
                }
                return title;
            },
            delete_friend_comment: function (info) {

                api.lgc.delete_goods_friend_comment({goods_comment_id:info.id}).then(function (value) {
                    info.is_active = false;
                    Magiclamp.mcAlert("提示", "评论已删除");
                    query_friend_goods_list(function () {
                        setTimeout(function () {
                            location.href = '#goods_id' + info.id;
                        }, 200);
                    });
                })
            },

            go_friend_comment_list_by_comment: function (goods_id) {
                location.href = './goods_friend_comment_list.html?goods_id=' + goods_id;
            },
            go_friend_comment_list: function (goods) {
                location.href = './goods_friend_comment_list.html?goods_id=' + goods.id;
            },
            open_goods_detail: function (goods) {
                location.href = './goods.html?goods_id=' + goods.id;
            },
            open_dispute_order: function (order, event) {
                event.stopPropagation();
                location.href = './dispute_order_list.html?order_id=' + order.id;
            },
            show_default_bar_list_fun2 : function (o) {
                default_data.show_default_bar_list = o;
            },

            go_to_goods_comment:function (comment) {
                var has_goods = false;
                _(default_data.friend_goods_list).each(function (item) {
                    if(item.id==comment.id){
                        has_goods = true;
                    }
                });
                if(!has_goods){
                    location.href = './goods_friend_comment_list.html?goods_id=' + comment.id;
                    return
                }
                location.href = '#goods_id' + comment.id;
                default_data.show_default_bar_list = false;
                comment.is_active = false;
                default_data.comment_line_list = _(default_data.comment_line_list).filter(function (item) {
                    return item.is_active;
                })
                api.lgc.clear_one_goods_by_comment_line({goods_id:comment.id}).then(function (value) {

                })
            },
            clear_comment_list:function (comment) {

                api.lgc.clear_goods_by_comment_line({}).then(function (value) {
                    default_data.show_default_bar_list = false;
                    query_goods_by_comment_line_list()
                })
            },
            page_back: function () {
                default_data.show_default_bar_list = false;
            }
        }
    });

    var last_center = null;
    var current_center = null;
    var last_geohash_level = 3;
    var download_live = {};

    function get_map_zoom_level() {
        var level = 3;
        if (get_map_zoom() < 5) {
            level = 1
        } else if (get_map_zoom() < 7) {
            level = 2
        } else if (get_map_zoom() < 11) {
            level = 3
        } else if (get_map_zoom() < 13) {
            level = 4
        } else if (get_map_zoom() < 15) {
            level = 5
        } else if (get_map_zoom() < 17) {
            level = 6
        }
        return level;
    }

    function show_host_by_location(lat, lng, geohash_level, parm, query_user_list) {
        // api.sys.query_host_by_gps_list({lo:map.center.lng(), la:map.center.lat()}).then(function (data) {
        if (!parm) {
            parm = {};
            parm.shi_ti = program_data.search_live_type;
        }
        parm.lo = lng;
        parm.la = lat;
        parm.level = geohash_level;
        parm.page_size = 100 - geohash_level * 10;
        api.sys.query_store_or_maishou_by_gps_list(parm).then(function (data) {
            last_geohash_level = geohash_level;
            if (query_user_list == null) {
                program_data.near_user_list = [];
            }

            _(data.result.list).each(function (item) {
                item.distance = GetDistance(lat, lng, item.la, item.lo);

                if (item.distance > 1) {
                    item.distance_str = "[" + parseInt(item.distance) + "千米]";
                } else {
                    item.distance_str = "[" + parseInt(item.distance * 1000) + "米]";
                }
                if (query_user_list == null) {
                    program_data.near_user_list.push(item);
                } else {
                    query_user_list.push(item)
                }

            });
            if (query_user_list != null) {
                return;
            }
            _(data.result.list).each(function (item) {
                if (download_live[item.id]) {
                    if (download_live[item.id].gps_time == item.gps_time) {
                        return;
                    }
                    download_live[item.id].la = item.la;
                    download_live[item.id].lo = item.lo;
                    download_live[item.id].live_status = item.live_status;
                    download_live[item.id].gps_time = item.gps_time;
                    // download_live[item.id].marker.setMap(null);
                    // download_live[item.id].marker = null;
                    download_live[item.id].hide();

                } else {
                    download_live[item.id] = item;
                }

            })
            _(download_live).each(function (item, key) {

                // if(item.icon_url && item.icon_url.indexOf("static2.mmggoo.com")>0){
                //     var image = baseConfig.host+"/sys/map_icon?icon_url="+encodeURI(item.icon_url);
                //     var beachMarker = new google.maps.Marker({
                //         position: {lat: item.la, lng: item.lo},
                //         label:item.realname,
                //         map: map,
                //         icon: image
                //     });
                // }else{
                //     var beachMarker = new google.maps.Marker({
                //         position: {lat: item.la, lng: item.lo},
                //         label:item.realname,
                //         map: map,
                //     });
                // }
                if (item.marker) {
                    item.marker.show();
                    return;
                }

                var image = "img2/mark022.png";
                if (item.t == 2) {
                    image = "img2/mark062.png"
                }
                if (item.t == 3) {
                    image = "img2/mark032.png"
                }
                // var beachMarker = new google.maps.Marker({
                //     position: {lat: item.la, lng: item.lo},
                //     label: item.realname,
                //     map: map,
                //     icon: image
                // });
                var label = new BMap.Label(item.realname, {offset:new BMap.Size(5,-5)});
                label.setStyle({"border":"0px","backgroundColor": "0.000000000001", "fontSize": "0.8rem"});
                var beachMarker = new BMap.Marker(new BMap.Point(item.lo, item.la), {enableDragging:false, icon:new BMap.Icon(image, new BMap.Size(10,22), {imageSize:new BMap.Size(10,22)})});
                // var beachMarker = new BMap.Marker(new BMap.Point(item.lo, item.la), {enableDragging:true, icon:new BMap.Icon(image, new BMap.Size(20,44))});
                beachMarker.setLabel(label);
                map.addOverlay(beachMarker);

                beachMarker.live_item = item;
                item.marker = beachMarker;
                download_live[item.id] = item;

                // beachMarker.addListener('click', function (e, maker) {
                beachMarker.addEventListener('click', function (e) {

                    var maker = e.target;
                    console.warn(1);
                    // if (map.getZoom() < 8) {
                    //     map.setZoom(8);
                    // }
                    // map.setCenter(beachMarker.getPosition());
                    // alert(this.live_item.realname);
                    setTimeout(function () {
                        program_data.show_live_list = true;
                    }, 100);

                    // program_data.show_live_list = !program_data.show_live_list;
                    // locationAddress(beachMarker.getPosition()).then(function (data) {
                    //     program_data.current_place = data;
                    // });
                    // show_near_live(beachMarker.getPosition().lat(), beachMarker.getPosition().lng());
                    show_near_live(maker.point.lat, maker.point.lng);
                });
                // beachMarker.addEventListener('dragend', function (e) {
                //
                //     var maker = e.target;
                //     map.panTo(new BMap.Point(maker.point.lng,maker.point.lat));
                //     maker.setPosition(new BMap.Point(maker.live_item.lo, maker.live_item.la));
                // });

                //
                // beachMarker.addListener('dblclick', function(e, maker) {
                //     if(map.getZoom()<14){
                //         map.setZoom(14);
                //     }
                //     map.setCenter(beachMarker.getPosition());
                //
                // });


            })

            sync_half_user();

        })
    }

    function query_host_or_goods_list() {
        // program_data.has_searched = true;
        if (program_data.search_type == 'goods') {
            var parm = {address_name: program_data.select_address2.name};

            parm.name = program_data.live_name;
            if (program_data.select_hot_search.id && program_data.select_hot_search.name == program_data.live_name) {
                parm.hot_search_id = program_data.select_hot_search.id;
            }
            if (program_data.select_address_goods_store2 && program_data.select_address_goods_store2.id) {
                parm.goods_store_id = program_data.select_address_goods_store2.id;
            }

            parm.is_only_address = program_data.select_address2_master;
            if (parm.is_only_address) {
                parm.store_address_id = program_data.select_address2.id;
            }
            parm.page_index = 1;
            program_data.goods_parm = parm;
            program_data.goods_parm_page_index = 1;
            program_data.near_goods_list = [];
            api.sys.query_goods_by_phone_hot_search_list(parm).then(function (data) {
                program_data.near_goods_count = data.result.page_count;
                _(data.result.list).each(function (item) {
                    program_data.near_goods_list.push(item);
                });

            });
        } else {
            var parm = {};
            if (program_data.search_address && program_data.search_address.name == "当前地图") {
                parm.la = get_map_center().lat();
                parm.lo = get_map_center().lng();
                parm.level = get_map_zoom_level();
            } else if (program_data.search_address) {
                parm.address_name = program_data.search_address.name;
            } else {
                parm.address_name = program_data.custom_search_address;
            }
            parm.live_name = program_data.live_name;
            _(program_data.search_shi_ti).each(function (item) {
                parm.shi_ti = item;
            });

            // _(download_live).each(function (item, key) {
            //     item.marker.setMap(null);
            //     item.marker = null;
            //     delete download_live[key];
            // });
            program_data.query_user_list = [];
            show_host_by_location(get_map_center().lat(), get_map_center().lng(), get_map_zoom_level(), parm, program_data.query_user_list);

        }
    };

    function show_near_live(lat, lng) {
        var arr = [];
        var max_distance = 1;
        if (get_map_zoom() == 1) {
            max_distance = 36000;
        } else if (get_map_zoom() == 2) {
            max_distance = 12000;

        } else if (get_map_zoom() == 3) {
            max_distance = 5000;

        } else if (get_map_zoom() == 4) {
            max_distance = 2000;

        } else if (get_map_zoom() == 5) {
            max_distance = 1200;

        } else if (get_map_zoom() == 6) {
            max_distance = 600;
        } else if (get_map_zoom() == 7) {
            max_distance = 300;
        } else if (get_map_zoom() == 8) {
            max_distance = 150;
        } else if (get_map_zoom() == 9) {
            max_distance = 90;
        } else if (get_map_zoom() == 10) {
            max_distance = 50;
        } else if (get_map_zoom() == 11) {
            max_distance = 30;
        } else if (get_map_zoom() == 12) {
            max_distance = 20;
        } else if (get_map_zoom() == 13) {
            max_distance = 10;
        } else if (get_map_zoom() == 14) {
            max_distance = 5;
        } else if (get_map_zoom() == 15) {
            max_distance = 2;
        }
        _(download_live).each(function (item, key) {
            item.distance = GetDistance(lat, lng, item.la, item.lo);
            if (item.distance > max_distance) {
                return;
            }

            if (item.distance > 1) {
                item.distance_str = "[" + parseInt(item.distance) + "千米]";
            } else {
                item.distance_str = "[" + parseInt(item.distance * 1000) + "米]";
            }

            arr.push(item);
        });
        arr = _(arr).sortBy(function (item) {
            if (item.live_type == 1) {
                return 0.006 + item.distance * 0.00000000001;
            }
            return item.distance;
        });
        program_data.near_user_list = arr;
    }

    function query_goods_type_list() {
        api.lgoods.query_goods_type_name_list({is_active: true}).then(function (data) {
            if (data.success) {
                program_data.goods_type_list = data.result.list;
                var arr = [];
                _(program_data.goods_type_list).each(function (item) {
                    if (!item.parent_id) {
                        item.sub_list = [];
                        arr.push(item);
                    }
                });
                program_data.goods_type_p_list = arr;

                _(program_data.goods_type_list).each(function (sub_item) {
                    if (sub_item.parent_id) {
                        _(program_data.goods_type_p_list).each(function (item) {
                            if (item.id == sub_item.parent_id) {
                                sub_item.class_name = "btn btn-default";
                                item.sub_list.push(sub_item);
                            }

                        });
                    }
                })
            }

        });
    }

    function query_store_address_list() {
        api.sys.query_store_address_list({is_active: true}).then(function (data) {
            if (data.success) {
                program_data.address_list = data.result.list;
                program_data.address_list2.push({name: "全部"});
                _(data.result.list).each(function (item) {
                    program_data.address_list2.push(item);
                })

                // select_address_item(program_data.address_list[0], true);
            }

        });
    }

    function query_hot_search_list() {
        api.sys.query_hot_search_phone_list({is_active: true}).then(function (data) {
            if (data.success) {
                program_data.hot_search_list = data.result.list;

                api.sys.query_goods_by_hot_search_list({}).then(function (value) {
                    program_data.near_goods_count = data.result.page_count;
                    program_data.near_goods_list = value.result.list;
                })
            }

        });
    }

    var current_address = {name: "全球", class_name: "btn-danger", selected: true};


    function open_chat_info(user_obj) {
        var user = {};
        if (user_obj.t == 1) {
            user.id = user_obj.user_id;
            user.imusername = user_obj.user__imusername;
            user.realname = user_obj.user__realname;
            user.goodsstore_id = user_obj.goodsstore_id;
        } else {
            user = user_obj;
        }
        program_data.show_live_list = false;
        program_data.show_host_detail = false;
        program_data.show_chat = true;
        if (!me_data.user.id) {
            window.login_mogu_ask(true).then(function () {
                // query_follow_by_user_list();

                create_chat(user);
            });
        } else {
            query_follow_by_user_list();

            create_chat(user);
        }
    }

    function sync_half_user() {
        var lat = get_map_center().lat();
        var lng = get_map_center().lng();
        var max_distance = 1;
        if (get_map_zoom() == 1) {
            max_distance = 36000;
        } else if (get_map_zoom() == 2) {
            max_distance = 12000;

        } else if (get_map_zoom() == 3) {
            max_distance = 5000;

        } else if (get_map_zoom() == 4) {
            max_distance = 2000;

        } else if (get_map_zoom() == 5) {
            max_distance = 1200;

        } else if (get_map_zoom() == 6) {
            max_distance = 600;
        } else if (get_map_zoom() == 7) {
            max_distance = 300;
        } else if (get_map_zoom() == 8) {
            max_distance = 150;
        } else if (get_map_zoom() == 9) {
            max_distance = 90;
        } else if (get_map_zoom() == 10) {
            max_distance = 50;
        } else if (get_map_zoom() == 11) {
            max_distance = 30;
        } else if (get_map_zoom() == 12) {
            max_distance = 20;
        } else if (get_map_zoom() == 13) {
            max_distance = 10;
        } else if (get_map_zoom() == 14) {
            max_distance = 5;
        } else if (get_map_zoom() == 15) {
            max_distance = 2;
        }
        var arr = []
        _(download_live).each(function (item, key) {

            item.distance = GetDistance(lat, lng, item.la, item.lo);
            if (item.distance > max_distance) {
                return;
            }

            if (item.distance > 1) {
                item.distance_str = "[" + parseInt(item.distance) + "千米]";
            } else {
                item.distance_str = "[" + parseInt(item.distance * 1000) + "米]";
            }

            if (item.t == 1) {
                arr.push(item);
            }

        });
        arr = _(arr).sortBy(function (item) {
            if (item.live_type == 1) {
                return 0.006 + item.distance * 0.00000000001;
            }
            return item.distance;
        });
        program_data.near_user_list_distance = arr;
    }

    function map_move_to(lat, lng, zoom) {
        // console.log(0);

        // map.setCenter({lat: lat, lng: lng});
        console.log('lat:'+lat+' lng:'+lng);
        // map.panTo(new BMap.Point(lng,lat));
        if (zoom) {
            map.setZoom(zoom);
            map.centerAndZoom(new BMap.Point(lng,lat),zoom);
        } else {
            map.setZoom(12);
            map.centerAndZoom(new BMap.Point(lng,lat),12);
        }


        // alert(this.live_item.realname);
        setTimeout(function () {
            program_data.show_live_list = false;
            program_data.show_search_content = false;
        });

    }

    function select_address_item(address, notmove) {
        program_data.select_address = address;
        program_data.select_address2 = address;
        // program_data.select_address2_master = true;
        program_data.select_address_goods_store = {}
        program_data.live_name = "";
        api.sys.query_goods_store_by_phone_store_address_list({store_address_id: address.id}).then(function (value) {
            program_data.address_goods_store_list = value.result.list;

        });
        if (!notmove) {
            map_move_to(address.lt, address.lg, address.zoom);
        }

    }

    function show_search() {
        program_data.show_search_content = true;
        program_data.show_live_list = false;

        if (program_data.select_address.id) {
            program_data.select_address2 = program_data.select_address;
        }

        program_data.select_address_goods_store2 = program_data.select_address_goods_store;

        query_host_or_goods_list();
    }

    var program_data = {
        baseConfig: baseConfig,
        page_index: 0,
        page_count: 0,
        program_list: [],
        near_user_list: [],
        near_user_list_distance: [],
        query_user_list: [],
        near_goods_list: [],
        near_goods_count: 0,
        live_type_list: [],
        goods_type_list: [],
        goods_type_p_list: [],
        goods_type_s_list: [],
        address_list: [],
        address_list2: [],
        address_goods_store_list: [],
        select_address_goods_store: {},
        select_address_goods_store2: {},
        select_address: {name: "选择地址"},
        select_hot_search: {},
        select_address2: {name: "全部"},
        select_address2_master: false,
        hot_search_list: [],
        select_goods_type: "全部",
        select_sub_goods_type: null,
        select_goods_type_id: null,
        has_searched: false,
        is_qita: false,
        goods_parm: {},
        goods_parm_page_index: 1,
        user_parm: {},
        user_parm_page_index: 1,
        live_name: "",
        search: "",
        address: "",
        show_search_content: false,
        show_search_content_half: true,
        search_content_half: 2,
        show_chat: false,
        show_host_info_obj: {},
        show_live_list: false,
        current_place: "",
        is_default: true,
        program_img: {},
        search_type: "goods",
        search_shi_ti: [],
        search_live_type: 2,
        hot_goods_type: [{name: "奶粉", class_name: "btn-default", selected: false, id: 13}, {
            name: "宝宝护理品",
            class_name: "btn-default",
            id: 15
        }, {name: '化妆品', class_name: "btn-default", id: 1}, {name: '鞋', class_name: "btn-default", id: 7}, {
            name: '包',
            class_name: "btn-default",
            id: 8
        }],// 奶粉，宝宝护理品，化妆品，鞋，包
        search_address: current_address,
        custom_search_address: "",
        search_address_list_1: [current_address, {name: "当前地图", class_name: "btn-default"}, {
            name: "潮汕",
            class_name: "btn-default"
        }],
        search_address_list_2: [{name: "香港", class_name: "btn-default"}, {
            name: "日本",
            class_name: "btn-default"
        }, {name: "韩国", class_name: "btn-default"}],
        live_map: {},

        user: {},
        show_talk: false,
        show_host_detail: false,
        show_img_talk: false,
        show_img_talk_more: false,
        show_pengyou_dongtai: false,
        show_pengyou_dongtai_images: false,
        all_pengyou_dongtai: [],
        show_contact: true,
        infoMap: {},
        recentSessMap: {},
        selToID: null,
        selKey: null,
        goodsstore_id: 0,
        contactlist: [],
        msglist: [],
        facelist: [],
        guanzhulist: [],
        guanzhudict: {},
        chat_user: null,
        chatcontent: "",
        live_status: false,
        program_id: null,

        live_config: {}
    };
    var tab_program = Vue.extend({
        template: "#tab_program",
        data: function () {
            return program_data;
        },
        methods: {
            show_head_img: show_head_img,
            price_filter: price_filter,

            select_address_item: select_address_item,

            select_address_goods_store_item: function (address) {
                program_data.select_address_goods_store = address;
                program_data.select_address_goods_store2 = address;
                program_data.live_name = "";
                map_move_to(address.la, address.lo);
            },

            go_goods_detail: function (goods) {
                var phone_dict = phone_type();
                var phone = 'android';
                if (phone_dict.is_ios) {
                    phone = 'ios';
                }
                if (!goods.liveprogram_id) {
                    goods.liveprogram_id = "";
                }
                if (goods.goodsstore_id) {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=" + goods.goodsstore_id + "&t=" + new Date().getTime();
                } else {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=0&t=" + new Date().getTime();
                }
            },
            go_goods_info_detail: function (goods_id) {
                location.href = 'goods.html?goods_id=' + goods_id
            },
            show_search: show_search,
            select_address_item2: function (address, is_move) {
                program_data.select_address2 = address;
                program_data.select_address_goods_store2 = {};
                program_data.select_address2_master = false;
                if (program_data.live_name) {
                    query_host_or_goods_list();
                }
            },
            select_hot_search_fun: function (address) {
                program_data.live_name = address.name;
                program_data.select_hot_search = address;
                program_data.select_address_goods_store2 = {};
                program_data.select_address2 = {name: "全部"}
                query_host_or_goods_list();
            },

            change_search_live_type: function (live_type) {
                _(download_live).each(function (item, key) {
                    if (item['t'] == 1) {
                        return;
                    }
                    // item.marker.setMap(null);
                    item.marker = null;
                    delete download_live[key];
                });
                map.clearOverlays();
                program_data.search_live_type = live_type;
                show_host_by_location(get_map_center().lat(), get_map_center().lng(), get_map_zoom_level());
            },

            change_search_half: function (half_type) {

                program_data.search_content_half = half_type;
                if (half_type == 2) {
                    program_data.show_search_content_half = true;
                    sync_half_user();
                } else {
                    program_data.show_search_content_half = false;
                }


            },
            hide_pengyou_list: function () {
                program_data.show_pengyou_dongtai = false;
            },
            up_pengyou: function (p) {
                api.sys.zan_news({news_id: p.id}).then(function (result) {
                    if (result.result.is_zan) {
                        p.up_num += 1;
                    }

                })
            },
            open_pengyou: function (p) {
                program_data.show_pengyou_dongtai = false;
                create_chat({imusername: p.user__imusername, realname: p.user__realname});
            },
            show_pengyou: function () {
                program_data.show_pengyou_dongtai = true;
                var host_ids = [];
                _(program_data.near_user_list).each(function (item) {
                    host_ids.push(item.id)
                });
                api.sys.query_news_by_hosts_list({user_ids: host_ids.join(",")}).then(function (result) {
                    program_data.all_pengyou_dongtai = [];
                    _(result.result.list).each(function (item) {
                        if (item.files_json) {
                            item.files_json = JSON.parse(item.files_json);

                            // item.files_json_length = item.files_json.length;
                        }
                        item.goods_num = 0;
                        if (item.goods1_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods2_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods3_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods4_id) {
                            item.goods_num += 1;
                        }
                        if (item.news_type == 2) {
                            item.video_obj = item.files_json[0];
                            item.video_pic = item.files_json[1];
                        }

                        program_data.all_pengyou_dongtai.push(item);
                    })
                });
                // $.getScript("data/pengyou_data.js", function() {
                //     program_data.all_pengyou_dongtai = [];
                //     _(pengyou_data_list).each(function (item) {
                //         if(item.files_json){
                //             item.files_json = JSON.parse(item.files_json);
                //
                //             // item.files_json_length = item.files_json.length;
                //         }
                //         item.goods_num = 0;
                //         if(item.goods1_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods2_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods3_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods4_id){
                //             item.goods_num += 1;
                //         }
                //
                //         program_data.all_pengyou_dongtai.push(item);
                //     })
                //     // program_data.all_pengyou_dongtai = pengyou_data_list;
                // });
            },
            show_big_pengyou_img: function (item, fileurl) {
                // program_data.show_pengyou_dongtai = false;
                program_data.show_pengyou_dongtai_images = true;
                var width = window.innerWidth
                    || document.documentElement.clientWidth
                    || document.body.clientWidth;
                var height = window.innerHeight
                    || document.documentElement.clientHeight
                    || document.body.clientHeight;
                setTimeout(function () {
                    var pswpElement = document.getElementById("all_pengyou_pswp");

                    var items = [];
                    var index = 0;

                    _(item.files_json).each(function (sub, i) {
                        items.push({src: baseConfig.qn_host + sub.fileurl, w: width, h: height})
                        if (sub.fileurl == fileurl) {
                            index = i;
                        }
                    })

                    var options = {
                        // optionName: 'option value'
                        // for example:
                        mainClass: 'pswp--minimal--dark',
                        index: index, // start at first slide

                    };

                    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                    gallery.listen('close', function () {
                        // program_data.show_pengyou_dongtai = true;
                        program_data.show_pengyou_dongtai_images = false;
                    });
                    gallery.init();
                }, 200);

            },
            play_video: function (dt) {
                dt.clicked = true;
                var v = document.getElementById("video" + dt.id);
                if (!dt.playing) {
                    _(program_data.all_pengyou_dongtai).each(function (item) {
                        if (item.id != dt.id && item.playing) {
                            var v2 = document.getElementById("video" + item.id);
                            v2.pause();
                            item.playing = false;
                        }
                    })
                    v.play();
                    dt.playing = true;
                } else {
                    v.pause();
                    dt.playing = false;
                }
            },
            show_diff_time: function (dt) {
                var start_time = moment();
                var now = moment(dt);

                var days = start_time.diff(now, 'days');
                start_time = start_time.subtract(days, 'days');
                var hours = start_time.diff(now, 'hours');
                start_time = start_time.subtract(hours, 'hours');
                var minutes = start_time.diff(now, 'minutes');
                if (days == 0) {
                    if (hours > 0) {
                        return hours + "小时前";
                    }
                    return minutes + "分钟前"
                } else {
                    return dt.substr(5, 11);
                }
            },
            hide_search: function () {
                program_data.select_goods_type_id = null;
                program_data.select_sub_goods_type = null;
                program_data.select_goods_type = "全部";
                program_data.goods_type_s_list = [];
                program_data.live_name = "";
                // program_data.show_search_content = false;

            },
            hide_search_pannel: function () {
                program_data.show_search_content = false;

            },

            select_address_fun: function (obj) {
                _(program_data.search_address_list_1).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                _(program_data.search_address_list_2).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                obj.class_name = "btn-danger";
                obj.selected = false;
                program_data.search_address = obj;
                program_data.is_qita = false;
                // program_data.custom_search_address = "";
            },
            select_address_fun_qita: function () {
                _(program_data.search_address_list_1).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                _(program_data.search_address_list_2).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                program_data.search_address = null;
                program_data.is_qita = true;
                // program_data.custom_search_address = "";
            },
            change_custom_search_address: function (address_name) {
                if (address_name) {
                    _(program_data.search_address_list_1).each(function (item) {
                        item.class_name = "btn-default";
                        item.selected = false;
                    });
                    _(program_data.search_address_list_2).each(function (item) {
                        item.class_name = "btn-default";
                        item.selected = false;
                    });
                    program_data.search_address = null;
                } else {
                    if (program_data.search_address == null) {
                        program_data.search_address = current_address;
                        current_address.selected = true;
                        current_address.class_name = "btn-danger";
                    }

                }
            },

            query_host_or_goods_reset: function () {
                _(program_data.hot_goods_type).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                _(program_data.search_address_list_1).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                _(program_data.search_address_list_2).each(function (item) {
                    item.class_name = "btn-default";
                    item.selected = false;
                });
                program_data.search_address = current_address;
                program_data.is_qita = false;
                current_address.selected = true;
                current_address.class_name = "btn-danger";
                program_data.custom_search_address = "";
                program_data.live_name = "";
                program_data.search_shi_ti = [];
                program_data.has_searched = false;

            },

            query_host_or_goods_list: query_host_or_goods_list,

            query_search_goods_list: function () {
                var parm = program_data.goods_parm;
                if (program_data.near_goods_count == program_data.goods_parm_page_index) {
                    Magiclamp.mcAlert("提示", "已到最后一页。", null, function () {

                    });
                    return;
                }
                program_data.goods_parm_page_index += 1;
                parm.page_index = program_data.goods_parm_page_index;
                api.sys.query_goods_by_phone_hot_search_list(parm).then(function (data) {
                    program_data.near_goods_count = data.result.page_count;
                    _(data.result.list).each(function (item) {
                        program_data.near_goods_list.push(item);
                    });

                });
            },

            query_search_user_list: function () {
                var parm = program_data.user_parm;
                program_data.user_parm_page_index += 1;
                parm.page_index = program_data.user_parm_page_index;
                api.sys.query_host_by_gps_list(parm).then(function (data) {
                    _(data.result.list).each(function (item) {
                        program_data.near_user_list.push(item);
                    });

                });
            },

            select_goods_type_fun: function (obj) {
                if (obj.selected == true) {
                    obj.class_name = "btn-default";
                    obj.selected = false;
                } else {
                    _(program_data.hot_goods_type).each(function (item) {
                        item.class_name = "btn-default";
                        item.selected = false;
                    });
                    obj.class_name = "btn-danger";
                    obj.selected = true;
                }

            },
            select_add: function (add) {
                program_data.select_address = add;
            },
            select_live_list: function () {
                program_data.show_search_content = false;

                _(download_live).each(function (item, key) {
                    // item.marker.setMap(null);
                    item.marker = null;
                    delete download_live[key];
                });
                map.clearOverlays();
                show_host_by_location(get_map_center().lat(), get_map_center().lng(), get_map_zoom_level());

            },
            hide_live_list: function () {
                setTimeout(function () {
                    program_data.show_live_list = false;
                });
            },
            map_move_to: map_move_to,
            edit_address: function () {
                Magiclamp.mcPrompt2("请输入地区", program_data.address, function (data) {
                    if (!data) {
                        return;
                    }
                    program_data.address = data;
                    codeAddress(program_data.address).then(function (data) {

                    });
                })
            },
            edit_goods: function () {
                Magiclamp.mcPrompt2("请输入商品", program_data.live_name, function (data) {
                    if (!data) {
                        return;
                    }
                    program_data.live_name = data;
                    program_data.show_search_content = true;
                    program_data.show_live_list = false;
                    query_host_or_goods_list();

                })
            },
            change_add: function () {
                // alert("1");
                // 创建地址解析器实例
                codeAddress(program_data.address).then(function (data) {

                });

                // var myGeo = new BMap.Geocoder();
                // // 将地址解析结果显示在地图上，并调整地图视野
                // myGeo.getPoint(program_data.address, function(point){
                //         if (point) {
                //             map.centerAndZoom(point, 8);
                //             map.addOverlay(new BMap.Marker(point));
                //         }
                //     }, "日本国");
                // b_init(program_data.address).then(function () {});
            },
            open_chat: open_chat,
            open_chat_info: open_chat_info,
            show_host_info: function (obj) {
                program_data.show_host_detail = true;
                program_data.show_host_info_obj = obj;

                program_data.show_live_list = true;
                program_data.show_chat = false;
            },
            hide_host_info: function (obj) {
                program_data.show_host_detail = false;
                program_data.show_host_info_obj = obj;

                program_data.show_live_list = false;
                program_data.show_chat = false;
            },
            change_face_btn: function () {
                chat_data.show_img_talk = !chat_data.show_img_talk;
                chat_data.show_img_talk_more = false;
            },
            change_more_btn: function () {
                chat_data.show_img_talk_more = !chat_data.show_img_talk_more;
                chat_data.show_img_talk = false;
            },
            changeData: function (event) {
                this.chatcontent = event.srcElement.innerHTML;
            },
            select_goodstype: function (name, goods_type_id) {

                program_data.select_goods_type = name;
                var arr = [];
                if (goods_type_id != null) {
                    _(program_data.goods_type_list).each(function (item) {
                        if (item.parent_id == goods_type_id) {
                            arr.push(item);
                        }
                    });
                }

                program_data.goods_type_s_list = arr;
                if (arr.length > 0) {
                    program_data.select_goods_type_id = arr[0].id;
                    program_data.select_sub_goods_type = arr[0].name;
                } else {
                    program_data.select_goods_type_id = null;
                    program_data.select_sub_goods_type = null;
                }
            },

            select_sub_goodstype: function (name, goods_type_id) {
                program_data.select_goods_type_id = goods_type_id;
                program_data.select_sub_goods_type = name;
            },

            show_host: show_host_by_location,
            timeline_str: function () {
                var t = new Date().getTime();
                t = parseInt(t / 1000 / 60 / 3);
                return "?t=" + t;
            },
            open_program: function (program_id) {
                if (!program_id) {
                    program_id = "";
                }
                var phone_type_obj = phone_type();
                if (phone_type_obj.is_wx) {
                    if (phone_type_obj.is_ios) {
                        location.href = 'play_ios.html?type=ios&program_id=' + program_id + "&t=" + new Date().getTime();
                    } else if (phone_type_obj.is_android) {
                        location.href = 'play_android.html?type=android&program_id=' + program_id + "&t=" + new Date().getTime();
                    } else {
                        // 非android 和 ios 手机上的微信浏览器
                    }
                } else {
                    if (phone_type_obj.is_ios) {
                        location.href = 'play_ios.html?type=ios&program_id=' + program_id + "&t=" + new Date().getTime();
                    } else if (phone_type_obj.is_android) {
                        location.href = 'play_android.html?type=android&program_id=' + program_id + "&t=" + new Date().getTime();
                    } else {
                        // 非 ios 和 android的 系统的其他浏览器
                    }
                }

            },
            search_by_livetype: function (livetype_id) {
                _(program_data.live_type_list).each(function (item) {
                    item.checked = false;
                    if (item.id == livetype_id) {
                        item.checked = true;
                    }
                });
                program_data.program_list = [];
                program_data.page_index = 0;
                program_data.page_count = 0;
                program_data.livetype_id = livetype_id;
                var parm = {
                    page_index: program_data.page_index + 1,
                    name: program_data.search,
                    livetype_id: program_data.livetype_id
                }
                if (parm.livetype_id == 0) {
                    delete parm.livetype_id
                    parm['is_hot'] = true;
                }
                api.lprogram.query_live_program_list(parm).then(function (data) {

                    $.each(data.result.list, function (index, item) {
                        item.current_config__data_json = JSON.parse(item.current_config__data_json);
                        if (item.repeat != '') {
                            item.repeat = JSON.parse(item.repeat);
                            var time_time = '';
                            var time_week = '周';
                            $.each(item.repeat, function (index, time) {
                                time_time = time.startTime + '-' + time.endTime;
                                if (time.week == 1) {
                                    time_week += '一、';
                                } else if (time.week == 2) {
                                    time_week += '二、';
                                } else if (time.week == 3) {
                                    time_week += '三、';
                                } else if (time.week == 4) {
                                    time_week += '四、';
                                } else if (time.week == 5) {
                                    time_week += '五、';
                                } else if (time.week == 6) {
                                    time_week += '六、';
                                } else if (time.week == 7) {
                                    time_week += '日、';
                                }
                            });
                            item.time_repeat = time_time;
                            item.time_week = time_week.slice(0, -1)
                        }

                    });

                    _(data.result.list).each(function (item) {
                        program_data.program_list.push(item);
                    });

                    program_data.page_index = data.result.page_index;
                    program_data.page_count = data.result.page_count;

                });
            },
            search_by_name: function () {
                program_data.program_list = [];
                program_data.page_index = 0;
                program_data.page_count = 0;
                var parm = {
                    page_index: program_data.page_index + 1,
                    name: program_data.search,
                    livetype_id: program_data.livetype_id
                }
                if (parm.livetype_id == 0) {
                    delete parm.livetype_id
                    parm['is_hot'] = true;
                }
                api.lprogram.query_live_program_list(parm).then(function (data) {

                    $.each(data.result.list, function (index, item) {
                        item.current_config__data_json = JSON.parse(item.current_config__data_json);
                        if (item.repeat != '') {
                            item.repeat = JSON.parse(item.repeat);
                            var time_time = '';
                            var time_week = '周';
                            $.each(item.repeat, function (index, time) {
                                time_time = time.startTime + '-' + time.endTime;
                                if (time.week == 1) {
                                    time_week += '一、';
                                } else if (time.week == 2) {
                                    time_week += '二、';
                                } else if (time.week == 3) {
                                    time_week += '三、';
                                } else if (time.week == 4) {
                                    time_week += '四、';
                                } else if (time.week == 5) {
                                    time_week += '五、';
                                } else if (time.week == 6) {
                                    time_week += '六、';
                                } else if (time.week == 7) {
                                    time_week += '日、';
                                }
                            });
                            item.time_repeat = time_time;
                            item.time_week = time_week.slice(0, -1)
                        }

                    });

                    _(data.result.list).each(function (item) {
                        program_data.program_list.push(item);
                    });

                    program_data.page_index = data.result.page_index;
                    program_data.page_count = data.result.page_count;

                });
            },
            load_more_program: function () {
                var parm = {
                    page_index: program_data.page_index + 1,
                    name: program_data.search,
                    livetype_id: program_data.livetype_id
                }
                if (parm.livetype_id == 0) {
                    delete parm.livetype_id
                    parm['is_hot'] = true;
                }
                api.lprogram.query_live_program_list(parm).then(function (data) {
                    $.each(data.result.list, function (index, item) {
                        item.current_config__data_json = JSON.parse(item.current_config__data_json);
                        if (item.repeat != '') {
                            item.repeat = JSON.parse(item.repeat);
                            var time_time = '';
                            var time_week = '周';
                            $.each(item.repeat, function (index, time) {
                                time_time = time.startTime + '-' + time.endTime;
                                if (time.week == 1) {
                                    time_week += '一、';
                                } else if (time.week == 2) {
                                    time_week += '二、';
                                } else if (time.week == 3) {
                                    time_week += '三、';
                                } else if (time.week == 4) {
                                    time_week += '四、';
                                } else if (time.week == 5) {
                                    time_week += '五、';
                                } else if (time.week == 6) {
                                    time_week += '六、';
                                } else if (time.week == 7) {
                                    time_week += '日、';
                                }
                            });
                            item.time_repeat = time_time;
                            item.time_week = time_week.slice(0, -1)
                        }

                    });
                    _(data.result.list).each(function (item) {
                        program_data.program_list.push(item);
                    });

                    program_data.page_index = data.result.page_index;
                    program_data.page_count = data.result.page_count;

                });
            },
            shengyudays: function (plan_start_time, live_status) {
                if (live_status == 7) {
                    return "正在直播";
                } else if (!plan_start_time) {
                    return "等待直播";
                } else {
                    var start_time = moment(plan_start_time);
                    var now = moment();
                    if (start_time.isBefore(now)) {

                        return "等待直播";
                    }
                    var days = start_time.diff(now, 'days');
                    start_time = start_time.subtract(days, 'days');
                    var hours = start_time.diff(now, 'hours');
                    start_time = start_time.subtract(hours, 'hours');
                    var minutes = start_time.diff(now, 'minutes');
                    if (days == 0) {
                        return "(剩余：" + now.subtract(hours).hours() + "小时)"
                    } else if (days < 0) {
                        return "等待直播";
                    } else {
                        return "(剩余：" + days + "天" + hours + '小时' + minutes + '分)';
                    }
                }

            },
            has_contact_list: function (selToId) {
                var h = _(chat_data.contactlist).find(function (item) {
                    if (item.SessionId == selToId) {
                        return true;
                    }
                })
                if (!h) {
                    return false;
                } else {
                    return !h.is_hide;
                }
            },
            has_contact_or_guanzhu_list: function (selToId) {
                var is_contact = false;
                var h = _(chat_data.contactlist).find(function (item) {
                    if (item.SessionId == selToId) {
                        return true;
                    }
                });
                if (!h) {
                    is_contact = false;
                } else {
                    is_contact = !h.is_hide;
                }

                if (is_contact) {
                    return true;
                } else {
                    return !!chat_data.guanzhudict[selToId];
                }


            },
            clearLoop: function () {
                // window.ontouchstart = null;
                clearInterval(chat_data.Loop);//再次清空定时器，防止重复注册定时器
            },
            close_chat: close_chat,
            send_chat: function () {
                var text = $("#chat_ele").html();
                onSendMsg(text, function () {
                    chat_data.chatcontent = "";
                    $("#chat_ele").html("");
                })
            },
            add_face: function (face) {
                $("#chat_ele").append(face[0]);
                chat_data.chatcontent += face[0];
            },
            upload: function (face) {
                uploadPic(face);
            },
            chuoyichuo: function () {
                onSendMsg("戳一戳", function () {
                })
            },
            show_history: function () {
                getPrePageC2CHistoryMsgs();
            },
            price_filter: price_filter,
            show_head_img: show_head_img,
            showDeleteButton: function (contact) {
                clearInterval(chat_data.Loop);//再次清空定时器，防止重复注册定时器
                chat_data.Loop = setTimeout(function () {

                    var msg = "";
                    var imusername = "";
                    if (contact.SessionIdKey) {
                        msg = "是否删除" + chat_data.infoMap[contact.SessionIdKey].name + "的会话？";
                        imusername = contact.SessionId;
                    } else {
                        msg = "是否删除" + contact.realname + "的会话？";
                        imusername = contact.imusername;
                    }
                    Magiclamp.mcConfirm("提示", msg, function () {

                    }, function () {
                        delChat(contact.SessionType, contact.SessionId, function (resp) {
                            _(chat_data.contactlist).each(function (item) {
                                if (contact.SessionId == item.SessionId) {
                                    item.is_hide = true;
                                }
                            })
                        });
                        api.sys.remove_follow_by_imusername_list({host_imusername: imusername}).then(function (item) {
                            query_follow_by_user_list();
                        })
                    })

                }, 300);

            },
            go_goods_detail: function (goods) {
                var phone_dict = phone_type();
                var phone = 'android';
                if (phone_dict.is_ios) {
                    phone = 'ios';
                }
                if (!goods.liveprogram_id) {
                    goods.liveprogram_id = "";
                }
                // location.href = 'goods.html?goods_id='+goods_id;
                if (goods.goodsstore_id) {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=" + goods.goodsstore_id + "&t=" + new Date().getTime();
                } else {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=0&t=" + new Date().getTime();
                }

            },
        }
    });

    var create_chat = function (user) {
        open_chat(webim.SESSION_TYPE.C2C, user.imusername, user.realname, user.goodsstore_id);
        pushHistory();
    };

    var query_follow_by_user_list = function () {
        api.sys.query_follow_by_user_list().then(function (res) {
            window.chat_data.guanzhulist = res.result.list;
            window.chat_data.guanzhudict = {};
            _(res.result.list).each(function (item) {
                window.chat_data.guanzhudict[item.imusername] = true;
            })
        })
    };


    window.chat_data = {
        baseConfig: baseConfig,
        user: {},
        show_talk: false,
        show_host_detail: false,
        show_img_talk: false,
        show_img_talk_more: false,
        show_pengyou_dongtai: false,
        show_pengyou_dongtai_images: false,
        all_pengyou_dongtai: [],
        show_contact: true,
        infoMap: {},
        recentSessMap: {},
        selToID: null,
        selKey: null,
        goodsstore_id: 0,
        contactlist: [],
        msglist: [],
        facelist: [],
        guanzhulist: [],
        guanzhudict: {},
        chat_user: null,
        chatcontent: "",
        live_status: false,
        program_id: null,

        live_config: {}

    };
    window.chat_data = program_data;

    window.tab_chat = Vue.extend({
        template: "#tab_chat",
        data: function () {
            return chat_data
        },
        methods: {
            create_chat: create_chat,
            price_filter: price_filter,
            show_head_img: show_head_img,
            showDeleteButton: function (contact) {
                clearInterval(chat_data.Loop);//再次清空定时器，防止重复注册定时器
                chat_data.Loop = setTimeout(function () {

                    var msg = "";
                    var imusername = "";
                    if (contact.SessionIdKey) {
                        msg = "是否删除" + chat_data.infoMap[contact.SessionIdKey].name + "的会话？";
                        imusername = contact.SessionId;
                    } else {
                        msg = "是否删除" + contact.realname + "的会话？";
                        imusername = contact.imusername;
                    }
                    Magiclamp.mcConfirm("提示", msg, function () {

                    }, function () {
                        delChat(contact.SessionType, contact.SessionId, function (resp) {
                            _(chat_data.contactlist).each(function (item) {
                                if (contact.SessionId == item.SessionId) {
                                    item.is_hide = true;
                                }
                            })
                        });
                        api.sys.remove_follow_by_imusername_list({host_imusername: imusername}).then(function (item) {
                            query_follow_by_user_list();
                        })
                    })

                }, 300);

            },
            go_goods_detail: function (goods) {
                var phone_dict = phone_type();
                var phone = 'android';
                if (phone_dict.is_ios) {
                    phone = 'ios';
                }
                if (!goods.liveprogram_id) {
                    goods.liveprogram_id = "";
                }
                // location.href = 'goods.html?goods_id='+goods_id;
                if (goods.goodsstore_id) {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=" + goods.goodsstore_id + "&t=" + new Date().getTime();
                } else {
                    location.href = 'play_' + phone + '.html?&show=goods&type=' + phone + '&program_id=' + goods.liveprogram_id + "&goodsstore_id=0&t=" + new Date().getTime();
                }

            },

            show_host: function () {
                chat_data.show_host_detail = true;
            },
            clearLoop: function () {
                // window.ontouchstart = null;
                clearInterval(chat_data.Loop);//再次清空定时器，防止重复注册定时器
            },
            close_chat: close_chat,
            change_face_btn: function () {
                chat_data.show_img_talk = !chat_data.show_img_talk;
                chat_data.show_img_talk_more = false;
            },
            change_more_btn: function () {
                chat_data.show_img_talk_more = !chat_data.show_img_talk_more;
                chat_data.show_img_talk = false;
            },
            changeData: function (event) {
                this.chatcontent = event.srcElement.innerHTML;
            },
            open_chat: open_chat,
            send_chat: function () {
                var text = $("#chat_ele").html();
                onSendMsg(text, function () {
                    chat_data.chatcontent = "";
                    $("#chat_ele").html("");
                })
            },
            add_face: function (face) {
                $("#chat_ele").append(face[0]);
                chat_data.chatcontent += face[0];
            },
            upload: function (face) {
                uploadPic(face);
            },
            chuoyichuo: function () {
                onSendMsg("戳一戳", function () {
                })
            },
            show_history: function () {
                getPrePageC2CHistoryMsgs();
            },
            open_program_goods_by_live_id: function (imusername) {
                api.lprogram.get_program_play_url({imusername: imusername}).then(function (data) {
                    var program_id = data.result.id;
                    var phone_type_obj = phone_type();
                    if (phone_type_obj.is_wx) {
                        if (phone_type_obj.is_ios) {
                            location.href = 'play_ios.html?type=ios&show=goods&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else if (phone_type_obj.is_android) {
                            location.href = 'play_android.html?type=android&show=goods&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else {
                            // 非android 和 ios 手机上的微信浏览器
                        }
                    } else {
                        if (phone_type_obj.is_ios) {
                            location.href = 'play_ios.html?type=ios&show=goods&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else if (phone_type_obj.is_android) {
                            location.href = 'play_android.html?type=android&show=goods&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else {
                            // 非 ios 和 android的 系统的其他浏览器
                        }
                    }
                });
            },
            open_program_by_live_id: function (imusername) {

                api.lprogram.get_program_play_url({imusername: imusername}).then(function (data) {
                    var program_id = data.result.id;
                    var phone_type_obj = phone_type();
                    if (phone_type_obj.is_wx) {
                        if (phone_type_obj.is_ios) {
                            location.href = 'play_ios.html?type=ios&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else if (phone_type_obj.is_android) {
                            location.href = 'play_android.html?type=android&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else {
                            // 非android 和 ios 手机上的微信浏览器
                        }
                    } else {
                        if (phone_type_obj.is_ios) {
                            location.href = 'play_ios.html?type=ios&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else if (phone_type_obj.is_android) {
                            location.href = 'play_android.html?type=android&program_id=' + program_id + "&t=" + new Date().getTime();
                        } else {
                            // 非 ios 和 android的 系统的其他浏览器
                        }
                    }
                });


            },
            query_guan_zhu_list: query_follow_by_user_list,
            add_guan_zhu: function (selToId) {
                api.sys.add_follow_by_imusername_list({host_imusername: selToId}).then(function (res) {
                    query_follow_by_user_list();
                })
            },
            remove_guan_zhu: function (selToId) {
                api.sys.remove_follow_by_imusername_list({host_imusername: selToId}).then(function (res) {
                    query_follow_by_user_list();
                })
            },
            has_contact_list: function (selToId) {
                var h = _(chat_data.contactlist).find(function (item) {
                    if (item.SessionId == selToId) {
                        return true;
                    }
                })
                if (!h) {
                    return false;
                } else {
                    return !h.is_hide;
                }
            },
            has_contact_or_guanzhu_list: function (selToId) {
                var is_contact = false;
                var h = _(chat_data.contactlist).find(function (item) {
                    if (item.SessionId == selToId) {
                        return true;
                    }
                });
                if (!h) {
                    is_contact = false;
                } else {
                    is_contact = !h.is_hide;
                }

                if (is_contact) {
                    return true;
                } else {
                    return !!chat_data.guanzhudict[selToId];
                }


            },
            hide_pengyou_list: function () {
                chat_data.show_pengyou_dongtai = false;
            },
            up_pengyou: function (p) {
                api.sys.zan_news({news_id: p.id}).then(function (result) {
                    p.up_num += 1;
                })
            },
            open_pengyou: function (p) {
                chat_data.show_pengyou_dongtai = false;
                create_chat({imusername: p.user__imusername, realname: p.user__realname});
            },
            show_pengyou: function (imusername) {
                chat_data.show_pengyou_dongtai = true;
                api.sys.query_news_by_users_list({imusernames: imusername}).then(function (result) {
                    chat_data.all_pengyou_dongtai = [];
                    _(result.result.list).each(function (item) {
                        if (item.files_json) {
                            item.files_json = JSON.parse(item.files_json);

                            // item.files_json_length = item.files_json.length;
                        }
                        item.goods_num = 0;
                        if (item.goods1_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods2_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods3_id) {
                            item.goods_num += 1;
                        }
                        if (item.goods4_id) {
                            item.goods_num += 1;
                        }
                        if (item.news_type == 2) {
                            item.video_obj = item.files_json[0];
                            item.video_pic = item.files_json[1];
                        }

                        chat_data.all_pengyou_dongtai.push(item);
                    })
                });
                // $.getScript("data/pengyou_data.js", function() {
                //     chat_data.all_pengyou_dongtai = [];
                //     _(pengyou_data_list).each(function (item) {
                //         if(item.files_json){
                //             item.files_json = JSON.parse(item.files_json);
                //
                //             // item.files_json_length = item.files_json.length;
                //         }
                //         item.goods_num = 0;
                //         if(item.goods1_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods2_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods3_id){
                //             item.goods_num += 1;
                //         }
                //         if(item.goods4_id){
                //             item.goods_num += 1;
                //         }
                //
                //         chat_data.all_pengyou_dongtai.push(item);
                //     })
                //     // program_data.all_pengyou_dongtai = pengyou_data_list;
                // });
            },
            show_big_pengyou_img: function (item, fileurl) {
                // chat_data.show_pengyou_dongtai = false;
                chat_data.show_pengyou_dongtai_images = true;
                var width = window.innerWidth
                    || document.documentElement.clientWidth
                    || document.body.clientWidth;
                var height = window.innerHeight
                    || document.documentElement.clientHeight
                    || document.body.clientHeight;
                setTimeout(function () {
                    var pswpElement = document.getElementById("chat_all_pengyou_pswp");

                    var items = [];
                    var index = 0;

                    _(item.files_json).each(function (sub, i) {
                        items.push({src: baseConfig.qn_host + sub.fileurl, w: width, h: height})
                        if (sub.fileurl == fileurl) {
                            index = i;
                        }
                    })

                    var options = {
                        // optionName: 'option value'
                        // for example:
                        mainClass: 'pswp--minimal--dark',
                        index: index, // start at first slide

                    };

                    var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
                    gallery.listen('close', function () {
                        // chat_data.show_pengyou_dongtai = true;
                        chat_data.show_pengyou_dongtai_images = false;
                    });
                    gallery.init();
                }, 200);

            },
            play_video: function (dt) {
                dt.clicked = true;
                var v = document.getElementById("video" + dt.id);
                if (!dt.playing) {
                    _(chat_data.all_pengyou_dongtai).each(function (item) {
                        if (item.id != dt.id && item.playing) {
                            var v2 = document.getElementById("video" + item.id);
                            v2.pause();
                            item.playing = false;
                        }
                    })
                    v.play();
                    dt.playing = true;
                } else {
                    v.pause();
                    dt.playing = false;
                }
            },
            show_diff_time: function (dt) {
                var start_time = moment();
                var now = moment(dt);

                var days = start_time.diff(now, 'days');
                start_time = start_time.subtract(days, 'days');
                var hours = start_time.diff(now, 'hours');
                start_time = start_time.subtract(hours, 'hours');
                var minutes = start_time.diff(now, 'minutes');
                if (days == 0) {
                    if (hours > 0) {
                        return hours + "小时前";
                    }
                    return minutes + "分钟前"
                } else {
                    return dt.substr(5, 11);
                }
            },

        }
    });

    window.toggleTabs = function (tabText) {
        var defer = $.Deferred();
        if (tabText == "tab_program_fl") {
            // home_data.currentView = "tab_program";
            // client_storage("page", "tab_program");
            // home_data.active = "tab_program";
            // window.show_map();
            // show_search();
            location.href = 'home_fenlei.html'
        } else {
            home_data.currentView = tabText;
            client_storage("page", tabText);
            if (tabText == "tab_program") {
                window.show_map();

            }else{
                window.clear_map();
                download_live = {};
            }

            if (tabText == "tab_chat") {
                program_data.show_live_list = false;
                query_follow_by_user_list();
                // if(!me_data.user.id){
                //     window.login_mogu_ask(true);
                // }

                pushHistory();

            }
            home_data.active = tabText;
            if (tabText == 'tab_default') {

                setTimeout(function () {
                    var elem = document.getElementById('jiaodiantu');
                    if (!elem) {
                        return;
                    }
                    // $(".xiaoyuandian li").eq(0).addClass("cur");
                    if (window.mySwipe == undefined) {
                        window.mySwipe = new Swipe(elem, {
                            //1秒
                            auto: 3000,
                            continuous: true,
                            callback: function (index, element) {
                                // $(".xiaoyuandian li").eq(index).addClass("cur").siblings().removeClass("cur");
                            }
                        });
                    }

                }, 1000);

                // window.default_page_imagelist = setInterval(function () {
                //
                // }, 1000);

            }
        }

        defer.resolve();
        return defer.promise();
    }

    window.home_data = {
        tab_programText: "tab_program",
        tab_programFlText: "tab_program_fl",
        tab_chatText: "tab_chat",
        tab_defaultText: "tab_default",
        tab_cartText: "tab_cart",
        tab_meText: "tab_me",
        currentView: "tab_program",
        chat_num: 0,
        all_unread: 0,
        is_default: true,
        active: 0
    };
    var home = new Vue({
        el: "#home",
        data: home_data,
        components: {
            tab_program: tab_program,
            tab_cart: tab_cart,
            tab_default: tab_default,
            tab_me: tab_me
        },
        methods: {
            query_un_pay_order_info_list: query_un_pay_order_info_list,
            query_pay_order_info_list: query_pay_order_info_list,
            query_goods_order_list: query_goods_order_list,
            toggleTabs: toggleTabs,
            go_order_detail: function (payorder_id) {
                location.href = './order-detail.html?payorder_id=' + payorder_id;
            },
            refresh_cart: function () {
                api.lgoods.query_cart_list().then(function (data) {
                    cart_data.cart_list = data.result.list

                    // tab_cart.checkAll();
                    cart_data.goods_ids = [];
                    home_data.chat_num = 0;
                    cart_data.cart_list.forEach(function (item) {
                        if (item.is_active) {
                            cart_data.goods_ids.push(item.goods_id);
                            home_data.chat_num += item.num;
                        }
                    });
                    cart_data.is_all = true;

                    // home_data.chat_num = cart_data.cart_list.length;
                });
                api.sys.query_goods_by_phone_hot_search_list({page_size: 15}).then(function (data) {
                    cart_data.goods_list = data.result.list;


                });
            }


        }
    });
    // var goto_app = window.sessionStorage.getItem("goto_app");
    // if (!goto_app) {
    //     Magiclamp.mcConfirm("提示", "是否前往APP？", null, function () {
    //         window.location.href = baseConfig.app_download_url;
    //     });
    //     window.sessionStorage.setItem("goto_app", "true");
    // }


    $(function () {
        query_default_page_image_wheel_list();
        query_goods_by_hao_ping_pro_home_list();
        query_goods_type_list();
        query_store_address_list();
        query_hot_search_list();

        window.show_map();


        window.login_mogu_ask(true).then(function (value) {
            var tabText = client_storage("page");
            if (tabText == "tab_program") {
                var current_imusername = client_storage("current_imusername");
                if (current_imusername) {
                    var user_obj = {};
                    user_obj.user__imusername = current_imusername;
                    user_obj.user__realname = client_storage("current_realname");
                    try {
                        user_obj.goodsstore_id = parseInt(client_storage("goodsstore_id"));
                    } catch (e) {
                        user_obj.goodsstore_id = 0;
                    }

                    user_obj.t = 1;

                    client_storage("current_imusername", "");
                    open_chat_info(user_obj);
                }

            }
        });
    });

    window.login_mogu_ask = function (must) {
        var defer = $.Deferred();
        login_mogu(function () {
            api.sys.my_userinfo().then(function (data) {
                me_data.user = data.result;
                chat_data.user = data.result;

                webimLogin(me_data.user.imusername, me_data.user.realname, me_data.user.imuser_sign, me_data.user.icon_url, function () {
                    defer.resolve();
                });

                share_home_link(me_data.user.id);

            });

            // var data = {"status_code": 0, "message": "", "dialog": 0, "success": true, "result": {"username": "1862223152", "division_proportion": 0, "imuser_sign": "eJw9j1FPgzAUhf-K0tcZ03YtHb7BnBOBbG4QHS8ES8GOAAXq4jT*d0cNvp7v5tzzfYMoONxmnLcfjU71RQlwNwMQ3MwMOIt*kG0zZhgiijAkExryKs2UkvkIEYEQEgtZ9B-LcgTh*rjynlcZ7XgZ7B3n5S3wa-eRxLuhiF0uL-6*bXy*xuUr7D1GHhzv3dn6p417vI8O*SlMQlzVVRSqry7azRNqo9Kztk8bFZ*bbp5M72QuGi0LKXozBy*RvaRMCMhsbE9HZm6a6XTRm9VTrmVttBHFV0eL0sVExKeSvUizQv8VM8asqyn4*QVpell5", "realname": "\u738b\u5065", "live_type": 0, "icon_url": "http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqUibck4XmH00OiauUnjanhuAD6dv1MAVnuTvb8LPGVORSVboialaIqsotgdeia0JXpglmV0ltN75A19w/132", "is_active": true, "sessionid": "yqt6nrd2uga3q2stskhhffaa8m5a8das", "email": "", "live_status": false, "is_live": false, "is_staff": false, "impassword": "128b95f604", "imusername": "12819857ee07929", "date_joined": "2018-03-20 11:29:12", "id": 128, "desc": ""}};
            // me_data.user = data.result;
            // chat_data.user = data.result;
            // webimLogin(me_data.user.imusername, me_data.user.realname, me_data.user.imuser_sign, me_data.user.icon_url);

            home.refresh_cart();

            // home.query_un_pay_order_info_list();
            // home.query_pay_order_info_list();
            // home.query_goods_order_list();

            query_follow_by_user_list();
            query_friend_goods_list();


        }, "home", null, must);
        return defer.promise();
    };

    window.show_map = function () {
        var lat = null;
        var lng = null;
        var zoom = null;
        if (current_center&&window.map) {
            lat = current_center.center.lat();
            lng = current_center.center.lng();
            zoom = current_center.zoom;

            _(download_live).each(function (item, key) {
                if (item.marker) {
                    // item.marker.setMap(null);
                    item.marker = null;
                    // item.marker.hide();
                }

            });
            map.clearOverlays();
        } else {
            lat = client_storage('lat');
            if (lat) {
                lat = parseFloat(lat);
            }
            lng = client_storage('lng');
            if (lng) {
                lng = parseFloat(lng);
            }
            zoom = client_storage('zoom');
            if (zoom) {
                zoom = parseInt(zoom);
            }
        }
        window.b_init(lat, lng, zoom).then(function () {
            last_center = {center: get_map_center(), zoom: get_map_zoom()};
            current_center = {center: get_map_center(), zoom: get_map_zoom};
            show_host_by_location(get_map_center().lat(), get_map_center().lng(), 2);
            map.addEventListener('moveend', function () {
                current_center = {center: get_map_center(), zoom: get_map_zoom()};
                console.log('lat:'+get_map_center().lat()+' lng:'+get_map_center().lng());
                client_storage('lat', get_map_center().lat());
                client_storage('lng', get_map_center().lng());
                client_storage('zoom', get_map_zoom());
                window.setTimeout(function () {
                    last_geohash_level = get_map_zoom_level();
                    var distance = GetDistance(get_map_center().lat(), get_map_center().lng(), last_center.center.lat(), last_center.center.lng());
                    console.info("移动：" + distance + "km" + " zoom:" + get_map_zoom());
                    sync_half_user();
                    if (last_geohash_level == 1) {
                        if (distance < 100) {
                            return;
                        }
                    } else if (last_geohash_level == 2) {
                        if (distance < 30) {
                            return;
                        }
                    } else if (last_geohash_level == 3) {
                        if (distance < 10) {
                            return;
                        }
                    } else if (last_geohash_level == 4) {
                        if (distance < 5) {
                            return;
                        }
                    } else if (last_geohash_level == 5) {
                        if (distance < 1.2) {
                            return;
                        }
                    } else if (last_geohash_level == 6) {
                        if (distance < 0.3) {
                            return;
                        }
                    }
                    var level = 3;
                    level = get_map_zoom_level();
                    last_center = {center: get_map_center(), zoom: get_map_zoom()};
                    console.info("查询");
                    show_host_by_location(get_map_center().lat(), get_map_center().lng(), level);
                }, 1000);


            });

            // map.addListener("click", function () {
            // })

        });
    }

    // query_goods_type_list();

    home_data.sessionid = GetQueryString('sessionid');
    if (home_data.sessionid) {
        home_data.sessionid_q = "sessionid=" + home_data.sessionid;
        client_storage('sessionid', home_data.sessionid);
    }


    // setTimeout(function () {
    //
    // }, 200);
    var current = client_storage("page");
    if (current) {
        home.toggleTabs(current);
    }


});

document.setTitle = function (t) {
    document.title = t;
    var i = document.createElement('iframe');
    i.src = '//m.baidu.com/favicon.ico';
    i.style.display = 'none';
    i.onload = function () {
        setTimeout(function () {
            i.remove();
        }, 9)
    }
    document.body.appendChild(i);
}

setTimeout(function () {
    window.addEventListener("popstate", function (e) {
        if (home_data.active == "tab_chat") {
            if (chat_data.show_host_detail) {
                chat_data.show_host_detail = false;
            } else if (chat_data.show_talk) {
                window.close_chat();
                pushHistory();
            } else if (chat_data.show_contact) {
                window.toggleTabs("tab_program");
            }
        } else if (home_data.active == "tab_program") {
            window.close();
        }
        // e.stop();
    }, false);


}, 300);

function pushHistory() {
    var state = {
        title: "title",
        url: "#"
    };
    window.history.pushState(state, "title", "#");
}

function imageClick(imgObj) {
    var imgUrls = imgObj.src;
    var imgUrlArr = imgUrls.split("#"); //字符分割
    var smallImgUrl = imgUrlArr[0];//小图
    var bigImgUrl = imgUrlArr[1];//大图
    var oriImgUrl = imgUrlArr[2];//原图
    // var bigPicDiv = document.getElementById('bigPicDiv');
    // bigPicDiv.innerHTML = '';
    // var span = document.createElement('span');
    // span.innerHTML = '<img class="img-thumbnail" src="' + bigImgUrl + '" />';
    // bigPicDiv.insertBefore(span, null);
    // $('#click_pic_dialog').modal('show');
    Magiclamp.mcImgPop(bigImgUrl);
}


function share_home_link(user_id) {
    api.sys.wx_js_sdk_info({url: location.href}).then(function (data) {
        var old_url = location.href.replace(/(sessionid=[a-z0-9A-Z]+)/g, "");
        if (old_url.indexOf("share_user_id=") > -1) {
            var share_url = old_url.replace(/(share_user_id=\d+)/g, "share_user_id=" + user_id);

        } else {
            if (old_url.indexOf("?") > -1) {
                var share_url = old_url + "&share_user_id=" + user_id;
            } else {
                var share_url = old_url + "?share_user_id=" + user_id;
            }

        }
        try {

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: 'wxd78bb63115a11db4', // 必填，公众号的唯一标识
                timestamp: data.result.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.result.noncestr, // 必填，生成签名的随机串
                signature: data.result.signature,// 必填，签名
                jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表
            });
            wx.error(function (res) {
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                console.log(res);
            });
            wx.ready(function () {
                var img_url = 'http://www.mmggoo.com/static/weixin/img2/icon.png';
                wx.onMenuShareTimeline({
                    title: '华迅直购', // 分享标题
                    link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: img_url, // 分享图标
                    success: function (res) {
                        // 用户确认分享后执行的回调函数

                        console.log(res);
                    },
                    cancel: function (res) {
                        // 用户取消分享后执行的回调函数
                        console.log(res);
                    }
                });
                wx.onMenuShareAppMessage({
                    title: '华迅直购', // 分享标题
                    desc: '华迅直购', // 分享描述
                    link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: img_url, // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function (res) {
                        // 用户确认分享后执行的回调函数
                        console.log(res);
                    },
                    cancel: function (res) {
                        // 用户取消分享后执行的回调函数
                        console.log(res);
                    }
                });


            });


        } catch (res) {
            console.log(res);
        }

    })

    var share_user_id = GetQueryString("share_user_id");
    if (share_user_id && share_user_id.length > 0) {
        api.sys.set_share_user_by_user({from_user_id: share_user_id}).then(function (value) {
        })
    }
}